package me.sauce.bitcoinwallet

import android.app.AlertDialog
import android.os.AsyncTask
import android.view.View
import android.widget.TextView
import me.sauce.bitcoinwallet.base.BaseActivity
import me.sauce.bitcoinwallet.key.Data
import me.sauce.bitcoinwallet.key.utils.RandomUtils
import java.lang.ref.WeakReference

/**
 * @author sauce
 * @since 2018/4/3
 */

class HomeActivity : BaseActivity() {
    override fun injectView(): View {
        return initRId(R.layout.activity_home)
    }

    override fun initView() {
        super.initView()
        setUPSeed()
    }

    private fun setUPSeed() {
        AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("欢迎")
                .setNegativeButton("倒入") { arg0, arg1 -> }
                .setPositiveButton("新建私钥") { arg0, arg1 ->
                    //configure new random seed
                    startMasterSeedTask()
                    showProgress(true)
                }
                .show()
    }

    private fun startMasterSeedTask() {
      val s=  ConfigureSeedAsyncTask(WeakReference(this))
        s.execute()
    }

    private class ConfigureSeedAsyncTask internal constructor(private val homeActivity: WeakReference<HomeActivity>) : AsyncTask<Void, Int, Data>() {

        override fun doInBackground(vararg params: Void): Data? {
            val activity = this.homeActivity.get()
            val data = Data()
            if (activity == null) {
                return null
            }
            val rawEntropy = ByteArray(128 / 8)
            val randomUtils = RandomUtils()
            randomUtils.nextBytes(rawEntropy)
            data.privateKey = String(rawEntropy)
            return data
            //            Bip39.MasterSeed masterSeed = Bip39.createRandomMasterSeed(activity._mbwManager.getRandomSource());
            //            try {
            //                WalletManager walletManager = activity._mbwManager.getWalletManager(false);
            //                walletManager.configureBip32MasterSeed(masterSeed, AesKeyCipher.defaultKeyCipher());
            //                return walletManager.createAdditionalBip44Account(AesKeyCipher.defaultKeyCipher());
            //            } catch (KeyCipher.InvalidKeyCipher e) {
            //                throw new RuntimeException(e);
            //            }
        }

        override fun onPostExecute(accountid: Data) {
            this.homeActivity.get()?.showProgress(false)
            this.homeActivity.get()?.findViewById<TextView>(R.id.tv_private_key)?.text=accountid.privateKey
        }
    }
}
